package com.mockapi.service;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mockapi.entity.ApiLog;
import com.mockapi.mapper.ApiLogMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

/**
 * API日志服务
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class ApiLogService {

    private final ApiLogMapper apiLogMapper;

    /**
     * 分页查询日志
     */
    public Page<ApiLog> page(Integer pageNum, Integer pageSize, String requestPath, String requestMethod, Integer responseStatus, String startTime, String endTime) {
        LambdaQueryWrapper<ApiLog> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(StrUtil.isNotBlank(requestPath), ApiLog::getRequestPath, requestPath)
                .eq(StrUtil.isNotBlank(requestMethod), ApiLog::getRequestMethod, requestMethod)
                .eq(responseStatus != null, ApiLog::getResponseStatus, responseStatus)
                .ge(StrUtil.isNotBlank(startTime), ApiLog::getCreatedAt, startTime)
                .le(StrUtil.isNotBlank(endTime), ApiLog::getCreatedAt, endTime)
                .orderByDesc(ApiLog::getCreatedAt);
        
        return apiLogMapper.selectPage(new Page<>(pageNum, pageSize), wrapper);
    }

    /**
     * 保存日志
     */
    public boolean save(ApiLog apiLog) {
        return apiLogMapper.insert(apiLog) > 0;
    }

    /**
     * 清理旧日志
     */
    public int cleanOldLogs(int days) {
        // 这里可以实现清理指定天数之前的日志
        // 由于MyBatis-Plus的限制，这里只是示例
        log.info("清理{}天前的日志", days);
        return 0;
    }

    /**
     * 获取今日日志数量
     */
    public long getTodayLogCount() {
        LambdaQueryWrapper<ApiLog> wrapper = new LambdaQueryWrapper<>();
        wrapper.ge(ApiLog::getCreatedAt, java.time.LocalDateTime.now().withHour(0).withMinute(0).withSecond(0));
        return apiLogMapper.selectCount(wrapper);
    }
} 